//
//  ChatHistoryViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-7-5.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "ChatHistoryViewController.h"

#import "ChatHistoryCell.h"
#import "ChatViewController.h"
#import "ParentInfo.h"
#import "NetworkAccessManager.h"
#import "UIAlertView+Kirinrin.h"

@interface ChatHistoryViewController ()
@property (strong, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;
@property(strong, nonatomic)NSArray *tableData;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end

@implementation ChatHistoryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //        self.title = @"家长列表";
    }
    return self;
}
-(id)init{
    self = [super init];
    if (self) {
        //        self.title = @"家长列表";
    }
    return self;
}

- (void)viewDidLoad
{
    NSLog(@"viewDidLoad");
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //    [self.tableView removeFromSuperview];
    self.activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    //    self.activityIndicator.color = [UIColor blackColor];
    self.activityIndicator.center = CGPointMake(self.view.center.x, 15);
    [self.activityIndicator startAnimating];
    //    self.activityIndicator.hidesWhenStopped = NO;
    [self.view addSubview:self.activityIndicator];
    
    [self loadRemoteData];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)loadRemoteData{
    NSArray *conversationList = [[EaseMob sharedInstance].chatManager conversations];
    NSArray* sorte = [conversationList sortedArrayUsingComparator:
                      ^(EMConversation *obj1, EMConversation* obj2){
                          EMMessage *message1 = [obj1 latestMessage];
                          EMMessage *message2 = [obj1 latestMessage];
                          if(message1.timestamp > message2.timestamp) {
                              return(NSComparisonResult)NSOrderedAscending;
                          }else {
                              return(NSComparisonResult)NSOrderedDescending;
                          }
                      }];
//    NSMutableArray *parentIdList = [[NSMutableArray alloc]initWithCapacity:sorte.count];
    NSMutableArray *parentList = [[NSMutableArray alloc]initWithCapacity:sorte.count];
    
    NSMutableString *parenIdString = [[NSMutableString alloc]init];
    
    for (int i=0; i< [sorte count]; i++) {
        EMConversation *conversation = sorte[i];
        
        [parenIdString appendString:conversation.chatter];
        if (i<[sorte count]-1) {
            [parenIdString appendString:@","];
        }
        
        [parentList addObject:[[ParentInfo alloc]initWithMessage:conversation]];
    }

    NSString *uriString = @"Parent/0/queryParents.json";
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey, @"parentId":parenIdString};
    
    [[NetworkAccessManager shareManager]POST:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            
            self.tableData = [ParentInfo updateParentListWithArray:responseObject[@"data"] parents:parentList];
            
            [self.tableView reloadData];
            [self.activityIndicator stopAnimating];
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
    }];
    
    
    
}


 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
 
    if ([segue.identifier isEqualToString: @"toChater"]) {
        ChatViewController *destViewController = segue.destinationViewController;
        ParentInfo *info = sender;
        destViewController.chatter = info.id;
        destViewController.chatterPhotoUrlString = info.photo;
        destViewController.navigationItem.title = info.name;
    }
    
}



#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"heightForRowAtIndexPath");
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ParentInfo *conversation = [self.tableData objectAtIndex:indexPath.row];
    
    [self performSegueWithIdentifier:@"toChater" sender:conversation];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"numberOfRowsInSection");
    return [self.tableData count];
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identify = @"ContactListCell";
    ChatHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];

    ParentInfo *parent = [self.tableData objectAtIndex:indexPath.row];
    cell.data = parent;
    return cell;
}

@end
